#include "Algorithm.h"


Algorithm::Algorithm(std::vector<State> &states)
{
	this->states = states;
	
	this->Cmax  = 0;
}

/*
Wyszukuje zadanie z maksymalnym q.
*/
State Algorithm::FindMaxQ(std::vector<State> &states,unsigned int &id)
{
	State max = states[0];
	id = 0;
	for(unsigned int i=1;i<states.size();i++)
	{
		if(max.q<states[i].q)
		{
			max = states[i];
			id = i;
		}
	}
	return max;
}

void Algorithm::SchragePmtn()
{
	std::vector<State> avaible;
	State maxQ;
	State current;

	int qTime = 0;
	int time = 0;
	unsigned int i = 0;

	while ( !states.empty() || !avaible.empty()) 
	{
		for(i =0; i<states.size(); i++)
		{

			if(time>=states[i].r) 
			{
				avaible.push_back(states[i]);
				states.erase(states.begin()+i);
				i=0;
			}
		}


		if(!avaible.empty())
		{
			maxQ = FindMaxQ(avaible,i);

			if(((maxQ.q > current.q)) && (current.p >= 1))
			{
				avaible.erase(avaible.begin()+i);
				avaible.push_back(current);
				current = maxQ;

			}
			else if(current.p == 0 )
			{
				avaible.erase(avaible.begin()+i);

				if(qTime>=current.p)
					qTime-=current.p;

				if(qTime <  current.q)
					qTime = current.q;

				current = maxQ;

			}

		}

		time++;
		if(current.p>=1)
			current.p --;

		if(qTime>=1)
			qTime--;
	}
	Cmax = time+qTime;
}
void Algorithm::Schrage()
{
	std::vector<State> avaible;
	State maxQ;
	int qTime = 0;
	int time = 0;
	unsigned int i = 0;

	while ( !states.empty() || !avaible.empty()) 
	{
		for(i =0; i<states.size(); i++)
		{

			if(time>=states[i].r) 
			{
				avaible.push_back(states[i]);
				states.erase(states.begin()+i);
				i=0;
			}
		}

		if(avaible.empty())
		{
			time++;
			if(qTime>=1)
				qTime--;
		}
		else
		{
			maxQ = FindMaxQ(avaible,i);
			if(qTime>=maxQ.p)
				qTime-=maxQ.p;

			if(qTime <  maxQ.q)
				qTime = maxQ.q;

			time += maxQ.p;

			done.push_back(maxQ);

			avaible.erase(avaible.begin()+i);
		}
	}
	Cmax = time+qTime;
}

std::vector<State> Algorithm::GetStates()
{
	return done;
}

int Algorithm::GetCmax()
{
	return Cmax;
}

Algorithm::~Algorithm()
{
}